package keystore;

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;

public class CertificateMaker {

	public CertificateMaker(String username, String password) {
		String keyStore = "ulla" + "keyStore";

		KeyPair keyPair = createKeyPair();
		/*
		// Create key and place it in the keystore
		keytool -genkey -alias %alias% -keyalg RSA -keysize 1048 -keystore %keystore% -storepass password

		// Create signing request
		keytool -certreq  -alias %alias% -keystore %keystore% -file %alias%.csr -storepass password 

		// Sign request and create certificate
		openssl x509 -req -in %alias%.csr -CA root-ca.crt -CAkey root-ca.key -out %alias%.crt -days 365 -CAcreateserial -CAserial ca.seq  

		// import CA cert to keystore 
		keytool -importcert -alias ca  -file root-ca.crt -keystore %keystore% -storepass password

		// import own cert to keystore 
		keytool -importcert -alias %alias% -keypass password -file %alias%.crt -keystore %keystore% -storepass password 

		// import own cert to truststore 
		keytool -importcert -alias %alias% -keypass password -file %alias%.crt -keystore %alias%TrustStore -storepass password 

		// import CA cert to truststore 
		keytool -importcert -alias ca -keypass password -file root-ca.crt -keystore %alias%TrustStore -storepass password 

		// import server cert to truststore
		keytool -importcert -alias server -keypass password -file server.crt -keystore %alias%TrustStore -storepass password

		// list keystore
		set list=
		set /P list=list keystore? [y/n] %=%
		if %list% == y (
		keytool -list -v -keystore %keystore% -storepass password
		)
		set list=
		set /P list=list trustStore? [y/n] %=%
		if %list% == y (
		keytool -list -v -keystore %alias%TrustStore -storepass password
		set /P list=Press enter to exit...%=%
		)*/
	}

	public KeyStore createKeyStore(String keyStoreName, String password) {
		try {
			KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
			keyStore.load(null, password.toCharArray());
			keyStore.store(new FileOutputStream(keyStoreName), password.toCharArray());
			return keyStore;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public KeyPair createKeyPair() {
		try {
			KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
			keyGen.initialize(1024);
			return keyGen.generateKeyPair();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

}
